package cn.jinjimi.app.managers;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.app.entity.AllPosterInfo;
import cn.jinjimi.app.poster.bean.PosterTemplate;
import cn.jinjimi.app.poster.fragment.PosterContainerFragment;
import cn.jinjimi.app.store.DatabaseManager;
import cn.jinjimi.app.bean.SharePrefKeys;

import java.lang.reflect.Type;
import java.util.List;

/**
 * Created by lforxeverc on 16/9/28.
 */

public class PosterCacheManager {
    private static volatile PosterCacheManager instance;

    private PosterCacheManager() {
    }

    public static PosterCacheManager getInstance() {
        if (instance == null) {
            synchronized (PosterCacheManager.class) {
                if (instance == null)
                    instance = new PosterCacheManager();
            }
        }
        return instance;
    }

    /*保存顶部分类*/
    public void saveCategory(int dataType,List<PosterTemplate> categories) {
        Gson gson = new Gson();
        String data = gson.toJson(categories);
        PreferenceManager.setData(dataType == PosterContainerFragment.DataType.INFORMATION_POSTER ? SharePrefKeys.PREF_POSTER_CATEGORY:SharePrefKeys.PREF_JINJU_CATEGORY, data);
    }


    /*获取顶部海报分类*/
    public List<PosterTemplate> getCategory(int dataType) {
        String raw = PreferenceManager.getStringData(dataType == PosterContainerFragment.DataType.INFORMATION_POSTER ? SharePrefKeys.PREF_POSTER_CATEGORY:SharePrefKeys.PREF_JINJU_CATEGORY);
        Gson gson = new Gson();
        Type type = new TypeToken<List<PosterTemplate>>() {
        }.getType();
        return gson.fromJson(raw, type);
    }

    /*根据category,subCategory,title保存fragment的数据*/
    public void savePosterList(int category, int subCategory, String title, String productId, AllPosterInfo data) {
        String key = getKey(category, subCategory, title, productId);
        DatabaseManager.getInstance().getCacheDao().saveCacheData(data, key, false);
    }

    /*根据category,subCategory,title获取fragment的数据*/
    public AllPosterInfo getPosterListBy(int category, int subCategory, String title, String productId) {
        String key = getKey(category, subCategory, title, productId);
        String raw = DatabaseManager.getInstance().getCacheDao().getCacheData(key, false);
        try {
            Gson gson = new Gson();
            return gson.fromJson(raw, AllPosterInfo.class);
        } catch (Exception e) {
            return AllPosterInfo.EMPTYSET;
        }

    }

    private String getKey(int category, int subCategory, String title, String productId) {
        return String.format("%s_%s_%d_%d", title, productId, category, subCategory);
    }

}
